﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Content;
using DotNetNuke.Entities.Content.Common;

namespace DotNetNuke.Modules.TaskManager.Components.Taxonomy
{
    public class Content
    {
        private const string ContentTypeName = "TaskManagerTask";

        public ContentItem CreateContentItem(Task objTask, int tabId)
        {
            var typeController = new ContentTypeController();
            var colContentTypes = (from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t);
            int contentTypeId;

            if (colContentTypes.Count() > 0)
            {
                var contentType = colContentTypes.Single();
                contentTypeId = contentType == null ? CreateContentType() : contentType.ContentTypeId;
            }
            else
            {
                contentTypeId = CreateContentType();
            }

            var objContent = new ContentItem
            {
                Content = objTask.TaskName + " " + objTask.TaskDescription,
                ContentTypeId = contentTypeId,
                Indexed = false,
                ContentKey = "tid=" + objTask.TaskId,
                ModuleID = objTask.ModuleID,
                TabID = tabId                
            };

            objContent.ContentItemId = Util.GetContentController().AddContentItem(objContent);

            var cntTerm = new Terms();
            cntTerm.ManageTaskTerms(objTask, objContent);

            return objContent;
        }

        public void UpdateContentItem(Task objTask, int tabId)
        {
            var objContent = Util.GetContentController().GetContentItem(objTask.ContentItemId);

            if (objContent == null) return;

            objContent.Content = objTask.TaskName + " " + objTask.TaskDescription;
            objContent.TabID = tabId;
            Util.GetContentController().UpdateContentItem(objContent);

            var cntTerm = new Terms();
            cntTerm.ManageTaskTerms(objTask, objContent);
        }

        public void DeleteContentItem(Task objTask)
        {
            if (objTask.ContentItemId <= Null.NullInteger) return;

            var objContent = Util.GetContentController().GetContentItem(objTask.ContentItemId);
            if (objContent == null) return;

            var cntTerm = new Terms();
            cntTerm.RemoveTaskTerms(objTask);

            Util.GetContentController().DeleteContentItem(objContent);
        }

        #region Private Methods

        private static int CreateContentType()
        {
            var typeController = new ContentTypeController();
            var objContentType = new ContentType { ContentType = ContentTypeName };

            return typeController.AddContentType(objContentType);
        }

        #endregion
    }
}